import { Button, Form, Input, message, Modal, Upload, UploadProps } from 'antd'
import { RcFile, UploadChangeParam, UploadFile } from 'antd/lib/upload'
import React, { useCallback, useEffect, useState } from 'react'
import { LoadingOutlined, PlusOutlined } from '@ant-design/icons'
import trademarkApi, { formDataModel } from '@/api/project'
export default function Index(props: any) {
  const { modal, trademark, getTrademarkList, showModal } = props

  const [form] = Form.useForm()
  const [loading, setLoading] = useState(false)
  // 品牌名称
  const [tmName, setTmName] = useState('')
  // 图片地址
  const [logoUrl, setLogoUrl] = useState<string>('')
  const [id, setId] = useState<undefined | number>(undefined)
  // 上传前
  const beforeUpload = (file: RcFile) => {
    const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png'
    if (!isJpgOrPng) {
      message.error('只能上传Jpg图片')
    }
    const isLt2M = file.size / 1024 / 1024 < 2
    if (!isLt2M) {
      message.error('最大为2m')
    }
    return isJpgOrPng && isLt2M
  }
  const normFile = (e: any) => {
    if (Array.isArray(e)) {
      return e
    }
    return e && e.fileList
  }
  const handleChange: UploadProps['onChange'] = (info: UploadChangeParam<UploadFile>) => {
    if (info.file.status === 'uploading') {
      return
    }
    setLogoUrl(info.file.response.data)
  }
  const uploadButton = (
    <div>
      {loading ? <LoadingOutlined /> : <PlusOutlined />}
      <div style={{ marginTop: 8 }}>上传LOGO</div>
    </div>
  )
  //   清空模态框
  const afterClose = () => {
    setTmName('')
    setLogoUrl('')
  }
  //   保存品牌
  const handleOk = async () => {
    try {
      await form.validateFields()
      await trademarkApi.AETrademark(formData())
      message.success('保存成功')
      showModal(false)
    } catch (error) {
      message.error(error)
    } finally {
      getTrademarkList()
    }
  }

  const handleCancel = () => {
    showModal(false)
  }
  const formData = useCallback((): formDataModel => {
    if (id) {
      return {
        id,
        tmName,
        logoUrl
      }
    } else {
      return {
        tmName,
        logoUrl
      }
    }
  }, [tmName, logoUrl, id])
  useEffect(() => {
    setTmName(trademark.tmName)
    setLogoUrl(trademark.logoUrl)
    setId(trademark.id)
  }, [trademark])
  return (
    <Modal
      afterClose={afterClose}
      width={800}
      open={modal}
      title={id ? '编辑品牌' : '添加品牌'}
      onOk={handleOk}
      onCancel={handleCancel}
      footer={[
        <Button key="back" onClick={handleCancel}>
          返回
        </Button>,
        <Button key="submit" type="primary" onClick={handleOk}>
          保存
        </Button>
      ]}
    >
      <Form
        name="basic"
        labelCol={{ span: 5 }}
        wrapperCol={{ span: 16 }}
        initialValues={{ remember: true }}
        // onFinish={onFinish}
        // onFinishFailed={onFinishFailed}
        autoComplete="off"
        form={form}
      >
        <Form.Item label="品牌名称" rules={[{ required: true, message: 'Please input your username!' }]}>
          <Input value={tmName} onInput={(e) => setTmName((e.target as any).value)} />
        </Form.Item>
        <Form.Item
          label="品牌LOGO"
          name="file"
          valuePropName="fileList"
          getValueFromEvent={normFile}
          rules={[
            {
              validator(rule, value) {
                if (!logoUrl) {
                  return Promise.reject('请上传文件')
                }
                return Promise.resolve()
              }
            }
          ]}
        >
          <Upload
            name="file"
            listType="picture-card"
            showUploadList={false}
            action="http://101.43.227.123:5555/app-prod/admin/product/upload"
            beforeUpload={beforeUpload}
            onChange={handleChange}
          >
            {logoUrl ? <img src={logoUrl} alt="file" style={{ width: '100%' }} /> : uploadButton}
          </Upload>
        </Form.Item>
      </Form>
    </Modal>
  )
}
